package com.demo.consumer;
import com.demo.controller.consumerFrom.OrderCreateConsumerFrom;
import com.demo.model.MovieOrder;
import com.demo.model.MovieTicketing;
import com.demo.service.MovieTicketingService;
import com.demo.service.impl.MovieOrderServiceImpl;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

@Component
@RocketMQMessageListener(consumerGroup = "order_create_consumer",topic = "order_create")
public class OrderCreateConsumer implements RocketMQListener<List<OrderCreateConsumerFrom>> {
    @Resource
    private MovieTicketingService movieTicketingService;
    @Resource
    private MovieOrderServiceImpl movieOrderService;
    @Autowired
    private RedisTemplate<String, Object> ort;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void onMessage(List<OrderCreateConsumerFrom> orderCreateConsumers) {
        BigInteger orderId = orderCreateConsumers.get(0).getOrderId();
        Object o = ort.opsForValue().get("order:id:" + orderId);
        if (o != null) {
            ArrayList<Integer> list = new ArrayList<>();
            for (OrderCreateConsumerFrom orderCreateConsumer : orderCreateConsumers) {
                ort.opsForHash().put("numberOfSessionsId:" + orderCreateConsumer.getNumberOfSessionsId().toString(), "ticketingId" + orderCreateConsumer.getTicketingId().toString(), "0");
                list.add(orderCreateConsumer.getTicketingId());
            }
            List<MovieTicketing> movieTicketings = movieTicketingService.listByIds(list);
            if (movieTicketings == null || movieTicketings.size() == 0) System.out.println("不存在对应的票务");
            for (MovieTicketing movieTicketing : movieTicketings) {
                movieTicketing.setOrderId(null);
            }
            boolean b = movieTicketingService.updateBatchById(movieTicketings);
            if (!b) System.out.println("票务修改失败");
            MovieOrder serviceById = movieOrderService.getById(orderId);
            serviceById.setOrderStart(7);
            boolean save = movieOrderService.updateById(serviceById);
            if (!save) System.out.println("订单状态修改失败");
        }else{
            System.out.println("订单已支付");
        }
    }
}
